package com.unionftech.common.recaptcha.aliyun

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams
import android.view.ViewGroup.VISIBLE
import android.view.Window
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ImageView
import android.widget.LinearLayout
import com.unionftech.common.R


class AliyunCaptChaDialog(config: AliyunCaptchaConfig) : Dialog(config.context!!) {
    private val mContext: Context = context
    private val mConfig = config
    private lateinit var mContentView: View
    private lateinit var mWebView: AliyunCaptchaWebView
    private lateinit var mLlCaptchaContent: LinearLayout
    private lateinit var mLoadingContainer: LinearLayout

    companion object {
        private const val NATIVE_NAME = "aliyunCaptchaJsInterface"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        createLoadUrl()
        setContent()
        setLayoutParams()
    }

    private fun createLoadUrl(): String {
        val stringBuilder = StringBuilder()
        stringBuilder.append("file:///android_asset/aliyunCaptchaIndex.html")
        stringBuilder.append("?sceneId=").append(mConfig.sceneId)
        stringBuilder.append("&prefix=").append(mConfig.prefix)
        stringBuilder.append("&language=").append(mConfig.language.language)
        return stringBuilder.toString()
    }

    private fun setLayoutParams() {
        window?.attributes?.gravity = Gravity.CENTER
        window?.attributes?.width = LayoutParams.MATCH_PARENT
        window?.attributes?.height = LayoutParams.MATCH_PARENT
        window?.setBackgroundDrawable(ColorDrawable(Color.parseColor("#80000000")))
        window?.decorView?.setPadding(0, 0, 0, 0)
    }

    private fun setContent() {
        mContentView = LayoutInflater.from(mContext).inflate(
            R.layout.aliyun_dialog_captcha,
            null
        )
        mContentView.findViewById<ImageView>(R.id.img_btn_close)
            .setOnClickListener {
                mConfig.listener?.onClose()
                dismiss()
            }
        mLlCaptchaContent = mContentView.findViewById(R.id.ll_captcha_content)
        mWebView = mContentView.findViewById(R.id.web_view)
        mLoadingContainer = mContentView.findViewById(R.id.loading_container)
        initWebView()
        setContentView(mContentView)
        setCancelable(true)
        setCanceledOnTouchOutside(true)
    }

    private fun initWebView() {
        mWebView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                mWebView.url?.let {
                    view?.loadUrl(it)
                }
                return true
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                mLlCaptchaContent.postDelayed({
                    mLlCaptchaContent.visibility = View.VISIBLE
                    mLoadingContainer.visibility = View.GONE
                }, 200)
            }
        }
        mWebView.loadUrl(createLoadUrl())
        val jsInterface = AliyunCaptchaJsInterface(mWebView,
            object : AliyunCaptchaListener {
                override fun onValidate(
                    captchaVerifyParam: String,
                    callBack: (captchaResult: Boolean) -> Unit
                ) {
                    mConfig.listener?.onValidate(captchaVerifyParam, callBack)
                }

                override fun onError(code: Int, msg: String?) {
                    mConfig.listener?.onError(code, msg)
                }

                override fun onClose() {
                    dismiss()
                }
            })
        mWebView.addJavascriptInterface(
            jsInterface,
            NATIVE_NAME
        )
    }

    override fun onStart() {
        super.onStart()
        mLlCaptchaContent.visibility = View.GONE
        setLayoutParams()
    }

    override fun show() {
        super.show()
        showLoading()
    }

    private fun showLoading() {
        mLoadingContainer.visibility = VISIBLE
    }

    override fun dismiss() {
        mWebView.loadUrl("about:blank")
        mWebView.removeJavascriptInterface(NATIVE_NAME)
        mWebView.parent?.let {
            if (it is ViewGroup) {
                it.removeView(mWebView)
            }
        }
        mWebView.removeAllViews()
        mWebView.destroy()
        super.dismiss()
    }
}